package com.company.cloud.mall.modules.data.service.impl;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import com.alibaba.fastjson.JSON;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.company.cloud.common.bean.BaseClientResult;
import com.company.cloud.common.bean.LoginSimpleUserInfo;
import com.company.cloud.common.utils.CheckUtils;
import com.company.cloud.common.utils.LocalDateTimeUtils;
import com.company.cloud.mall.constant.ShopConstant.OrderTypeEnum;
import com.company.cloud.mall.modules.api.constant.OrderRefundStateEnum;
import com.company.cloud.mall.modules.api.constant.OrderReturnStateEnum;
import com.company.cloud.mall.modules.api.constant.OrderStateEnum;
import com.company.cloud.mall.modules.data.controller.req.OrderStatisticParam;
import com.company.cloud.mall.modules.data.mapper.ShopOrderStatisticMapper;
import com.company.cloud.mall.modules.data.models.OrderStatusDataModel;
import com.company.cloud.mall.modules.data.models.ShopSummaryData;
import com.company.cloud.mall.modules.data.service.ShopStatisticService;
import com.company.cloud.user.modules.api.request.RegisterNumDataRequest;
import com.company.cloud.user.modules.api.response.RegisterNumDataResponse;
import com.company.cloud.user.modules.api.service.UserDataRemoteService;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.util.StrUtil;

@Service
public class ShopStatisticServiceImpl implements ShopStatisticService {

    @Autowired
    private ShopOrderStatisticMapper shopOrderStatisticMapper;
    @Autowired
    private UserDataRemoteService userDataRemoteService;


    /**
     * 订单统计
     */
    private void _orderStatistic(ShopSummaryData data, List<OrderStatusDataModel> orderStatusData, String type) {

        if (CollectionUtils.isEmpty(orderStatusData)) {
            return;
        }

        //成交额(元)
        BigDecimal Fund = BigDecimal.ZERO;

        //成交订单数(笔)
        Integer OrderNum = 0;

//		//总订单金额(元)
//		BigDecimal TotalFund=BigDecimal.ZERO;
//		//总订单数(笔)
//		Integer TotalOrderNum=0;

        for (OrderStatusDataModel item : orderStatusData) {
            //待付款
            //交易关闭
            if (OrderStateEnum.OSE_Pay.getCode().equals(item.getStatus())
                    || OrderStateEnum.OSE_Close.getCode().equals(item.getStatus())) {
//				if(CheckUtils.hasBigDecimal(item.getFund())) {
//					TotalFund=TotalFund.add(item.getFund());
//				}
//				if(CheckUtils.hasInt(item.getNum())) {
//					TotalOrderNum=TotalOrderNum+item.getNum();
//				}
            } else if (OrderStateEnum.OSE_Check.getCode().equals(item.getStatus())
                    || OrderStateEnum.OSE_Send.getCode().equals(item.getStatus())
                    || OrderStateEnum.OSE_Send_Part.getCode().equals(item.getStatus())
                    || OrderStateEnum.OSE_Receiving.getCode().equals(item.getStatus())
                    || OrderStateEnum.OSE_Complete.getCode().equals(item.getStatus())
            ) {
                //待审核 //待发货 //部分发货 //待收货 //交易完成

                if (CheckUtils.hasBigDecimal(item.getFund())) {
//					TotalFund=TotalFund.add(item.getFund());
                    Fund = Fund.add(item.getFund());
                }
                if (CheckUtils.hasInt(item.getNum())) {
//					TotalOrderNum=TotalOrderNum+item.getNum();
                    OrderNum = OrderNum + item.getNum();
                }
            }
        }
//		data.setTotalFund(TotalFund);
//		data.setTotalOrderNum(TotalOrderNum);

        if ("today".equals(type)) {
            System.out.println("12312445645411++++++++++++++++++++" + Fund + ":" + OrderNum + ":" + type);
            data.setFund(Fund);
            data.setOrderNum(OrderNum);
            if (CheckUtils.hasInt(OrderNum)) {
                data.setCustFund(Fund.divide(new BigDecimal(OrderNum)));
            }
        }

        if ("total".equals(type)) {
            data.setTotalFund(Fund);
            data.setTotalOrderNum(OrderNum);
        }

    }

    /**订单统计*/
//	private void _orderStatistic(ShopSummaryData data,String companyNo,String date) {
//		List<OrderStatusDataModel> orderStatusData=shopOrderStatisticMapper.orderStatus(
//				new QueryWrapper<OrderStatusDataModel>()
//				.eq(StringUtils.hasText(date),"date_format(order_date ,'%Y-%m-%d' )", date)
//				.eq(StringUtils.hasText(companyNo), "company_no", companyNo)
//				.groupBy("status")
//		);
//		this._orderStatistic(data, orderStatusData);
//	}


    /**
     * 退款统计
     */
    private void _afterStatistic(ShopSummaryData data, String dateStart, String dateEnd, String type) {
        List<OrderStatusDataModel> refundsDataList = shopOrderStatisticMapper.refundStatus(
                new QueryWrapper<OrderStatusDataModel>()
                        .ge("cdt", dateStart)
                        .le("cdt", dateEnd)
                        .groupBy("state")
        );

        List<OrderStatusDataModel> returnsDataList = shopOrderStatisticMapper.returnsStatus(
                new QueryWrapper<OrderStatusDataModel>()
                        .ge("cdt", dateStart)
                        .le("cdt", dateEnd)
                        .groupBy("state")
        );
        this.__afterStatistic__(data, refundsDataList, returnsDataList, type);
    }

    /**
     * 退款统计
     */
    private void _afterStatistic(ShopSummaryData data, String date, String type) {
        List<OrderStatusDataModel> refundsDataList = shopOrderStatisticMapper.refundStatus(
                new QueryWrapper<OrderStatusDataModel>()
                        .eq(StringUtils.hasText(date), "date_format(cdt ,'%Y-%m-%d' )", date)
                        .groupBy("state")
        );

        List<OrderStatusDataModel> returnsDataList = shopOrderStatisticMapper.returnsStatus(
                new QueryWrapper<OrderStatusDataModel>()
                        .eq(StringUtils.hasText(date), "date_format(cdt ,'%Y-%m-%d' )", date)
                        .groupBy("state")
        );
        this.__afterStatistic__(data, refundsDataList, returnsDataList, type);

    }

    private void __afterStatistic__(ShopSummaryData data, List<OrderStatusDataModel> refundsDataList, List<OrderStatusDataModel> returnsDataList, String type) {
        //总
//			BigDecimal TotalReturnFund=BigDecimal.ZERO;
//			Integer TotalReturnNum=0;

        //成功
        BigDecimal ReturnFund = BigDecimal.ZERO;
        Integer ReturnNum = 0;

        if (!CollectionUtils.isEmpty(refundsDataList)) {
            for (OrderStatusDataModel item : refundsDataList) {
                //资金返还(退款中)
                //完成(资金到账)
                if (OrderRefundStateEnum.ORFS_Refund.getCode().equals(item.getStatus())
                        || OrderRefundStateEnum.ORFS_Complete.getCode().equals(item.getStatus())) {
                    if (CheckUtils.hasBigDecimal(item.getFund())) {
//							TotalReturnFund=TotalReturnFund.add(item.getFund());
                        ReturnFund = ReturnFund.add(item.getFund());
                    }
                    if (CheckUtils.hasInt(item.getNum())) {
//							TotalReturnNum=TotalReturnNum+item.getNum();
                        ReturnNum = ReturnNum + item.getNum();
                    }
                } else {
//						if(CheckUtils.hasBigDecimal(item.getFund())) {
//							TotalReturnFund=TotalReturnFund.add(item.getFund());
//						}
//						if(CheckUtils.hasInt(item.getNum())) {
//							TotalReturnNum=TotalReturnNum+item.getNum();
//						}
                }
            }
        }

        if (!CollectionUtils.isEmpty(returnsDataList)) {
            for (OrderStatusDataModel item : returnsDataList) {
                //资金返还(退款中
                //完成(资金到账)
                if (OrderReturnStateEnum.ORFPS_Refund.getCode().equals(item.getStatus())
                        || OrderReturnStateEnum.ORFPS_Complete.getCode().equals(item.getStatus())) {
                    if (CheckUtils.hasBigDecimal(item.getFund())) {
//							TotalReturnFund=TotalReturnFund.add(item.getFund());
                        ReturnFund = ReturnFund.add(item.getFund());
                    }
                    if (CheckUtils.hasInt(item.getNum())) {
//							TotalReturnNum=TotalReturnNum+item.getNum();
                        ReturnNum = ReturnNum + item.getNum();
                    }
                } else {
//						if(CheckUtils.hasBigDecimal(item.getFund())) {
//							TotalReturnFund=TotalReturnFund.add(item.getFund());
//						}
//						if(CheckUtils.hasInt(item.getNum())) {
//							TotalReturnNum=TotalReturnNum+item.getNum();
//						}
                }
            }
        }

        if ("total".equals(type)) {
            data.setTotalReturnFund(ReturnFund);
            data.setTotalReturnOrderNum(ReturnNum);
        }

        if ("today".equals(type)) {
            data.setReturnFund(ReturnFund);
            data.setReturnOrderNum(ReturnNum);
        }

    }


    @Override
    public ShopSummaryData shopSummaryStatistic2Date(String dateStart, String dateEnd) {

        ShopSummaryData data = new ShopSummaryData();

        //总订单统计
        List<OrderStatusDataModel> totalOrderStatusData = shopOrderStatisticMapper.orderStatus(
                new QueryWrapper<OrderStatusDataModel>()
                        .eq("order_type", OrderTypeEnum.OT_General.getCode())
                        .ge("order_date", "2019-01-01 01:01:01")
                        .le("order_date", DateUtil.now())
                        .groupBy("status")
        );

        this._orderStatistic(data, totalOrderStatusData, "total");

        //订单统计
        List<OrderStatusDataModel> orderStatusData = shopOrderStatisticMapper.orderStatus(
                new QueryWrapper<OrderStatusDataModel>()
                        .eq("order_type", OrderTypeEnum.OT_General.getCode())
                        .ge("order_date", dateStart)
                        .le("order_date", dateEnd)
                        .groupBy("status")
        );
        this._orderStatistic(data, orderStatusData, "today");

        //售后总统计
        this._afterStatistic(data, "2019-01-01 01:01:01", DateUtil.now(), "total");

        //售后统计
        this._afterStatistic(data, dateStart, dateEnd, "today");

        //新增用户
        RegisterNumDataRequest rndr = new RegisterNumDataRequest();
        rndr.setStartDate(dateStart);
        rndr.setEndDate(dateEnd);

        BaseClientResult<RegisterNumDataResponse> result = userDataRemoteService.registerUserNum(rndr);
        RegisterNumDataResponse numResponse = BaseClientResult.getResultData(result, new RegisterNumDataResponse());
        data.setAddUserNum(numResponse.getNum() == null ? 0 : numResponse.getNum());
        return data;
    }

    @Override
    public ShopSummaryData shopSummaryStatistic2Date(String date, LoginSimpleUserInfo userInfo) {
        ShopSummaryData data = new ShopSummaryData();
        //订单统计
        List<OrderStatusDataModel> orderStatusData = shopOrderStatisticMapper.orderStatus(
                new QueryWrapper<OrderStatusDataModel>()
                        .eq("order_type", OrderTypeEnum.OT_General.getCode())
                        .eq(StringUtils.hasText(date), "date_format(order_date ,'%Y-%m-%d' )", date)
                        .groupBy("status")
        );

        this._orderStatistic(data, orderStatusData, "today");

        //售后统计
        this._afterStatistic(data, date, "today");
        //注册数统计
        RegisterNumDataRequest regParams = new RegisterNumDataRequest();
        regParams.setStartDate(StrUtil.format("{} 00:00:00", date));
        regParams.setEndDate(StrUtil.format("{} 23:59:59", date));
        BaseClientResult<RegisterNumDataResponse> regNumResult = userDataRemoteService.registerUserNum(regParams);
        RegisterNumDataResponse regNumData = BaseClientResult.getResultData(regNumResult);
        data.setAddUserNum(regNumData == null ? 0 : regNumData.getNum());
        return data;
    }


    /**
     * 订单统计
     */
    @Override
    public List<ShopSummaryData> orderStatisticByDate(OrderStatisticParam param, LoginSimpleUserInfo userInfo) {
        String format = null;
        if ("Y".equals(param.getStatisticWay())) {
            format = "%Y";
        } else if ("M".equals(param.getStatisticWay())) {
            format = "%Y-%m";
        } else if ("W".equals(param.getStatisticWay())) {
            format = "%Y-%v";
        } else if ("D".equals(param.getStatisticWay())) {
            format = "%Y-%m-%d";
        }
        LocalDateTime startDt = LocalDateTimeUtils.parse_yyyyMMdd(param.getStartDate());
        LocalDateTime endDt = LocalDateTimeUtils.parse_yyyyMMdd(param.getEndDate());
        List<OrderStatusDataModel> osdmList = shopOrderStatisticMapper.orderStatusByDate(startDt, endDt, format);

        Map<String, ShopSummaryData> dataMap = new HashMap<String, ShopSummaryData>();

        if (!CollectionUtils.isEmpty(osdmList)) {
            Map<String, List<OrderStatusDataModel>> osdmMap = new HashMap<String, List<OrderStatusDataModel>>();
            osdmList.forEach(osdm -> {
                List<OrderStatusDataModel> list = osdmMap.get(osdm.getD());
                if (list == null) {
                    list = new ArrayList<OrderStatusDataModel>();
                    osdmMap.put(osdm.getD(), list);
                }
                list.add(osdm);
            });

            osdmMap.forEach((date, orderList) -> {
                ShopSummaryData ssd = dataMap.get(date);
                if (ssd == null) {
                    ssd = new ShopSummaryData(date);
                    dataMap.put(date, ssd);
                }
                this._orderStatistic(ssd, orderList, "today");
            });
        }

        List<ShopSummaryData> data = new ArrayList<ShopSummaryData>();
        dataMap.forEach((k, v) -> {
            data.add(v);
        });
        return data;
    }


}
